<?php
/**
 * 登录
 */
namespace app\controller\applets;
use think\facade\Log;
use app\controller\applets\BaseController;
use think\Request;
use app\service\TokenService;
use app\model\TempUsers;

class Login extends BaseController{


    public function __construct() {


    }

    /**
     * 没有登录的用户获取token
     * @return [array]         [数组]
     */
	public function getToken(Request $input){
		$result=TempUsers::getTempUsers();
		if(empty($result)){
			return $this->return_err(['msg'=>'没有临时用户了']);
		}
		$token=TokenService::createToken($result->id);
		TokenService::saveToken($token,$result);
		//更新用户状态为使用中
		TempUsers::updateTempUsersStatus($result->id);
		
		return $this->return_msg(['data'=>['token'=>$token]]);

	}

    /**
     * 刷新token
     * @return [array]         [数组]
     */
	public function refreshToken(Request $input){
		$tokenKey=$input->param('token');
		if(!isset($tokenKey) || empty($tokenKey)){
			return $this->return_err(['msg'=>'缺少参数token']);
		}

		$result=TokenService::verifyToken($tokenKey);
		if($result){
			return $this->return_err(['msg'=>'token有效']);
		}

		$token=TokenService::getToken($tokenKey);
		if(!$token){
			return $this->return_err(['msg'=>'创建token失败']);
		}

		//更新用户状态为没有使用
		TempUsers::updateTempUsersStatus($result->id,$status=0);

		return $this->return_msg(['data'=>['token'=>$token]]);
	}

    /**
     * 检查token
     * @return [array]         [数组]
     */
	public function verifyToken(Request $input){
		$result=TokenService::verifyToken($input->param('token'));
		if(!$result){
			return $this->return_err(['msg'=>'token已失效']);
		}
		return $this->return_msg();
	}


	//登录
	public function login(Request $input){
		$result=LoginService::login($input->param());
		if(!$result){
			return $this->return_err();
		}
		return $this->return_msg();
	}
	
	//注册
	public function register(Request $input){
		$result=LoginService::register($input->param());
		if(!$result){
			return $this->return_err();
		}
		return $this->return_msg();
	}




}
